package com.xzzz.common.base.util.easyexcel;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;

/**
 * 大数值转换
 * Excel 数值长度位15位, 大于15位的数值转换位字符串
 */
@Slf4j
public class ExcelBigNumberConvert implements Converter<Long> {

    /**
     * 被转换的 Java 类型, 如果导出时, java数据对象的类型为 Long, 则会进行相关处理.
     */
    @Override
    public Class<Long> supportJavaTypeKey() {
        return Long.class;
    }

    /**
     * 转换后的String类型
     */
    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    /**
     * 将值转换为Long
     */
    @Override
    public Long convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        Long defaultValue = null;
        if (cellData.getData() == null) {
            return defaultValue;
        }

        // long to long
        if (cellData.getData() instanceof Long) {
            return (Long) cellData.getData();
        }

        // number to long
        if (cellData.getData() instanceof Number) {
            return ((Number) cellData.getData()).longValue();
        }

        // string to long
        final String valueStr = toStr(cellData.getData());
        if (StrUtil.isEmpty(valueStr)) {
            return defaultValue;
        }
        try {
            // 支持科学计数法
            return new BigDecimal(valueStr.trim()).longValue();
        } catch (Exception e) {
            return defaultValue;
        }
    }

    @Override
    public WriteCellData<Object> convertToExcelData(Long object, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        if (!ObjectUtils.isEmpty(object)) {
            String str = toStr(object);
            if (str.length() > 15) {
                return new WriteCellData<>(str);
            }
        }
        WriteCellData<Object> cellData = new WriteCellData<>(new BigDecimal(object));
        cellData.setType(CellDataTypeEnum.NUMBER);
        return cellData;
    }

    public static String toStr(Object value) {
        if (null == value) {
            return null;
        }
        if (value instanceof String) {
            return (String) value;
        }
        return value.toString();
    }

}
